<template>
    <el-dialog
      v-model="visible"
      :title="bookId!='[object PointerEvent]' ? bookFormerly : '新增书籍'"
      width="600px"
      @close="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <!-- 书名 -->
        <el-form-item
          label="书名"
          prop="bookName"
          class="required-label"
        >
          <el-input v-model="formData.bookName" clearable />
          <!-- <el-input v-model="formData.bookName" :disabled="bookId!='[object PointerEvent]'" clearable /> -->
        </el-form-item>
  
        <!-- 作者 -->
        <el-form-item
          label="作者"
          prop="author"
          class="required-label"
        >
          <el-input v-model="formData.author" clearable />
          <!-- <el-input v-model="formData.author" :disabled="bookId!='[object PointerEvent]'" clearable /> -->
        </el-form-item>
        <!-- 书籍类型 -->
        <el-form-item label="类型" class="required-label" prop="chanceBookType">
          <el-cascader @change="clearCascader" :options="options" v-model="chanceBookType" clearable />
        </el-form-item>
        <!-- 书籍简介 -->
        <el-form-item label="书籍简介">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            resize="none"
          />
        </el-form-item>
  
        <!-- 封面图 -->
        <el-form-item
          label="封面图"
          prop="coverUrl"
          class="required-label"
        >
          <el-upload
            action="#"
            accept="image/*"
            :show-file-list="false"
            :auto-upload="false"
            @change="(file) => handleUpload(file, 'coverUrl')"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">已上传：{{ formData.coverUrl || '暂无' }}</div>
              <img v-if="formData.coverUrl!=''" :src="formData.coverUrl" style="width: 100px; height: 150px">
            </template>
          </el-upload>
        </el-form-item>
  
        <!-- 电子书 -->
        <el-form-item
          label="电子书"
          prop="fileUrl"
          class="required-label"
        >
          <el-upload
            action="#"
            accept=".txt"
            :show-file-list="false"
            :auto-upload="false"
            @change="(file) => handleUpload(file, 'fileUrl')"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">已上传：{{ formData.fileUrl || '暂无' }}</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
  
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleSave"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import api from "../../api/api"
  
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true
    },
    bookId: {
      type: String,
      default: ''
    },
  options: { // 新增 props 用于接收书籍类型选项
    type: Array,
    default: () => []
  }
    
  })
  
  const emit = defineEmits(['update:visible', 'save'])
  
  // 表单引用（用于验证）
  const formRef = ref(null)
  const chanceBookType=ref([])
  const filesName=ref()
  // 表单数据
  const bookFormerly=ref()
  const formData = ref({
    bookId:'',
    bookName: '',
    author: '',
    bookType: 0,
    description: '',
    coverUrl: '', // 图片上传后的地址
    fileUrl: ''   // 文件上传后的地址
  })
  // 监听 visible 变化，重置表单验证状态

  // 监听 bookName 变化，获取图书详情
  watch(
    () => props.visible,
    async (newVisible) => {
      if (newVisible && props.bookId!='[object PointerEvent]') {
        try {
          // 获取图书详情接口
          const response = await api.post('/getAdminBookDetail', { bookId: props.bookId })
          const bookDetail = response.data
          console.log("bookDetail",bookDetail)
          // 设置表单数据
          bookFormerly.value=bookDetail.book_name
          formData.value = {
            bookId:bookDetail.book_id,
            bookName: bookDetail.book_name,
            author: bookDetail.book_author,
            description: bookDetail.book_introduce,
            coverUrl: bookDetail.book_url,
            fileUrl: bookDetail.book_file
          }
          chanceBookType.value = [
            bookDetail.category_parent_type, 
            bookDetail.category_type
          ]
          formRef.value.clearValidate()
          // alert(chanceBookType.value)
        } catch (error) {
          console.error('获取图书详情失败:', error)
          ElMessage.error('获取图书详情失败')
        }
      } else if (!newVisible) {
        // 弹窗关闭时重置表单
        resetForm()
      }
    }
  )

  function clearCascader(value){
  if(value==null){
    chanceBookType.value=[]
  }
}
const checkBookNameExist = async (bookName) => {
  try {
    const response = await api.post('/checkBookExist', { bookName: bookName });
    return response.data;  // 假设后端返回 true 表示存在，false 表示不存在
  } catch (error) {
    console.error('检查书名失败:', error);
    return false;
  }
};
  // 验证规则
  const rules = {
    bookName: [
    { required: true, message: '请输入书名', trigger: 'blur' },
    // {
    //   validator: async (rule, value, callback) => {
    //     // 如果是修改模式，不需要检查重名（因为可能是原名）
    //     if (props.bookName != '[object PointerEvent]') {
    //       callback();
    //       return;
    //     }
        
    //     // 如果是新增模式，需要检查重名
    //     if (props.bookName == '[object PointerEvent]') {
    //       const exists = await checkBookNameExist(value);
    //       if (exists) {
    //         callback(new Error('该书名已存在'));
    //       } else {
    //         callback();
    //       }
    //     } else {
    //       callback();
    //     }
    //   },
    //   trigger: 'blur'
    // }
    ],
    author: [
      { required: true, message: '请输入作者', trigger: 'blur' }
    ],
    chanceBookType: [ // 修改prop匹配绑定值
    { 
      required: true,
      validator: (rule, value, callback) => {
        // console.log('级联选择器的值:', chanceBookType.value)
        chanceBookType.value.length == 2 
          ? callback() 
          : callback(new Error('请选择完整分类'))
      },
      trigger: 'change'
    }
  ],
    coverUrl: [
      { required: true, message: '请上传封面图', trigger: 'change' }
    ],
    fileUrl: [
      { required: true, message: '请上传电子书', trigger: 'change' }
    ]
  }
  const uploadFile = async (file) => {
  // 创建 FormData 对象
  const formDataFile = new FormData();
  formDataFile.append('file', file.raw);  // 将文件添加到 formData 中
  
  try {
    // 发送 POST 请求上传文件
    const response = await api.post('/file/upload', formDataFile, {
      headers: {
        'Content-Type': 'multipart/form-data',  // 必须指定为multipart/form-data
      },
    });

    // 处理返回的响应
    console.log('上传成功后的返回值:', response.data);
    filesName.value=response.data.data
  } catch (error) {
    console.error('Error uploading file:', error);
  }
};
  // 模拟上传处理（待替换为实际接口）
  const handleUpload = async (file, type) => {
    console.log("file:", file);
    
    // 这里模拟上传成功后的回调
    if (!file) {
        return;
    }
    // 等待 uploadFile(file) 执行完成后再继续
    await uploadFile(file);

    // 执行上传完成后的逻辑
    formData.value[type] = filesName.value; // 文件上传后的地址
    console.log(formData.value[type]);
};
  
  // 保存处理
  const handleSave = async () => {
    try {
      // 触发表单验证
      await formRef.value.validate()
    //   if (props.bookName == '[object PointerEvent]') {
    //   const exists = await checkBookNameExist(formData.value.bookName);
    //   if (exists) {
    //     ElMessage.error('该书名已存在');
    //     return;
    //   }
    // }
      formData.value.bookType= Number(chanceBookType.value[1]);
      console.log("点击保存",formData.value)
      // 验证通过后提交
      emit('save', formData.value)
      emit('update:visible', false)
      resetForm()
    } catch (error) {
      ElMessage.error('请填写所有必填项')
    }
  }
  
  // 取消处理（保持不变）
  const handleCancel = () => {
    emit('update:visible', false)
    resetForm()
  }
  
  // 重置表单（保持不变）
  const resetForm = () => {
    formData.value = {
      bookId:'',
      bookName: '',
      author: '',
      description: '',
      coverUrl: '',
      fileUrl: ''
    }
    chanceBookType.value=[]
  }
  </script>
  
  <style scoped>
  /* 必填项红色星号 */
  .required-label :deep(.el-form-item__label::before) {
    content: '*';
    color: red;
    margin-right: 4px;
  }
  </style>